#encoding: utf-8
require 'open-uri'
require 'hpricot'
ALLOWED_CHANS = %w[0chan.ru 2-ch.ru] #so we have to define methods for each chan
MAX_THREADS = 12
module Chan_0chan 
  URL = "http://0chan.ru/"
  def Chan_0chan::threads_list(section)
    full_url = URL + section + '/'
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "Да ты же уебок"
    end
    threads = []
    page.search("div[@id*=thread]").each do |div|
      #file.puts div.attributes["id"]
      threads << /\d+/.match(div.attributes["id"])
    end
    threads
  end

  def Chan_0chan::op_post(section,threadid)
    full_url = URL + section + "/res/#{threadid}.html"
    begin
      chanthread = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "Да ты же уебок"
    end
    (chanthread/"div.postmessage").first.inner_text
  end

  #this one is too slow, but it works.
  def Chan_0chan::old_list(section)
    threads = threads_list(section)
    list = ""
    post_max_length = 100
    for i in 0..9 do
      list += '#' + threads[i].to_s + ' ' + (text = op_post(section,threads[i])).force_encoding("UTF-8")[0..post_max_length-1].gsub(/\n/,"")
      (list += '...') if text.length > post_max_length
      list += "\n"
    end
    list
  end

  def Chan_0chan::list(section,n)
    full_url = URL + section + '/'
    begin
      page = Hpricot(open(full_url))
    rescue
      return "Wrong section"
    end
    msg = ''
    post_max_length = 100
    threads = page/"div[@id*=thread]"
    (0..n-1).each do |i| 
      link = ((threads[i]/"div.postnode").first/"span.reflink"/"a").first.attributes["href"]
      text = (threads[i]/"div.postmessage").first.inner_text
      msg += "#{URL}#{link[1..-1]} " + (text = text.force_encoding("UTF-8").gsub(/\n/,' '))[0..post_max_length-1] 
      msg += '...' if text.length > post_max_length
      msg += "\n"
    end
    msg
  end

  def Chan_0chan::lastpost(section)
    full_url = URL + section + "/"
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "#{section}: 404"
    end

    lastpostnode = ((page/"div[@id*=thread]").first/"div.postnode").last
    link = (lastpostnode/"span.reflink"/"a").first.attributes["href"]
    text = (lastpostnode/"div.postmessage").inner_text
    {
      :link => "#{URL}#{link[1..-1]}",
      :text => text.gsub(/\n/," ")
    }

  end

  def Chan_0chan::randpost(section)
    full_url = URL + section + "/"
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "Some error in randpost"
    end

    randpostnode = ((page/"div[@id*=thread]").shuffle.first/"div.postnode").shuffle.last
    link = (randpostnode/"span.reflink"/"a").first.attributes["href"]
    text = (randpostnode/"div.postmessage").inner_text
    {
      :link => "#{URL}#{link[1..-1]}",
      :text => text.gsub(/\n/," ")
    }
  end
end


module Chan_2ch
  URL = "http://2-ch.ru/"
  def Chan_2ch::lastpost(section)
    full_url = URL + section + "/"
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "#{section}: 404"
    end
    page = page.to_s.force_encoding ("UTF-8")
   firstthread_answers = page.match /<a href=".+?">Ответ<\/a>.*?<a href=".+?">Ответ\<\/a>/
   posts = firstthread_answers[0]
   html = Hpricot posts
   lastpost = (html/"table").last
   link = URL + (lastpost/"span.reflink"/"a").first.attributes["href"][1..-1]
   text = (lastpost/"p").inner_text.force_encoding("UTF-8")
    {
      :link => link,
      :text => text.gsub(/\n/," ")
    }
  end

  def Chan_2ch::randpost section
    full_url = URL + section + "/"
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "#{section}: 404"
    end
    lastpost = (page/"table").shuffle.first
    p link = URL + (lastpost/"span.reflink"/"a").first.attributes["href"][1..-1]
    p text = (lastpost/"p").inner_text.force_encoding("UTF-8")
    {
      :link => link,
      :text => text.gsub(/\n/," ")
    }
  end

  def Chan_2ch::list section, n
    full_url = URL + section + "/"
    begin
      page = Hpricot(open(full_url))
    rescue #OpenURI::HTTPError
      return "#{section}: 404"
    end
    post_max_length = 100
    n = MAX_THREADS if n > MAX_THREADS
    msg =""
    page = page.to_html
    threads = page.split ("<hr />")
    threads.map! do |x|
      x = Hpricot x
      x.search("table").remove
      x
    end
    threads = threads.drop 2
    threads[0...n].each do |x|
      url = URL + (x/"span.reflink"/"a").first.attributes["href"][1..-1]
      text = (x/"p").first.inner_text
      text.force_encoding("utf-8").gsub!(/\n/,' ')
      msg += "#{url} " + text[0..post_max_length-1] 
      msg += '...' if text.length > post_max_length
      msg += "\n"
    end
    msg.force_encoding("utf-8")
  end
end
  class ImageBoard
  def initialize(chan="0chan.ru")
    @chan = chan
  end

  def lastpost section
    case @chan
    when "0chan.ru"
      Chan_0chan::lastpost section 
    when "2-ch.ru"
      Chan_2ch::lastpost section
    end
  end
  def randpost section
    case @chan
    when "0chan.ru"
      Chan_0chan::randpost section 
    when "2-ch.ru"
      Chan_2ch::randpost section
    end
  end

  def list section, n = 10
    case @chan
    when "0chan.ru"
      Chan_0chan::list section, n 
    when "2-ch.ru"
      Chan_2ch::list section, n
    end
  end
end



test = 0
if test == 1 then
  file = File.open("output.htm","w")
  board = ImageBoard.new "2-ch.ru"
  print board.list("hw",10)
  #file.puts "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>"
  #file.puts board.list("hw",10)
end

